#include "../../source/server.hpp"
#include <unordered_map>
#include <vector>
using namespace std;
eventLoop loop(60);
uint64_t nowId = 0;
unordered_map<uint64_t, std::shared_ptr<connection>> connections;
loopThreadPool* loopPool = new loopThreadPool(&loop, 2);

void protocol(const ptrConnection& pcon, Buffer& buf)
{
    // 这里需要将读取的数据清空
    buf.readerIdxGo(buf.getReadAbleSize());
    string msg = "hello, I'm server";
    pcon->send(msg.c_str(), msg.size());
}

void svrClose(const ptrConnection& pcon)
{
    int id = pcon->id();
    if (!connections.count(id))
    {
        lg(Warning, "connection already close");
        return;
    }
    lg(Info, "close the id: %d from map", id);
    connections.erase(id);
}


void onNewCon(int newfd)
{
    // 为新连接创建新的connection
    nowId++;
    lg(Info, "new ....");
    std::shared_ptr<connection> newCon = std::make_shared<connection>(loopPool->getLoop(), nowId, newfd);
    connections[nowId] = newCon;
    newCon->setProtocolCb(protocol);
    newCon->setSvrConCloseCb(svrClose);
    newCon->startInactiveFree(5);
    newCon->establish();
}


int main()
{

    loopPool->init();
    acceptor svr(&loop, 8080);
    svr.setNewConnectFunc(onNewCon);
    svr.start();
    loop.init();
    loop.start();
}